import axios from 'axios';
import { Message } from 'element-ui';
import store from '@/store/index';
import router from '@/router';

// 创建axios实例
const service = axios.create({
  baseURL: '/api',
  timeout: 5000,
  headers: {
    'Authorization': store.state.token
  }
});

// request 拦截器
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code == '1001') {
      // alert('1001啦！！！')
      // 遇见1001就跳转到登录页面
      router.push({
        name: '登录'
      });
    }

    // if the custom code is not 20000, it is judged as an error.
    if (response.status !== 200) {
      Message({
        message: 'Ajax错误',
        type: 'error',
        duration: 5 * 1000
      });

      return Promise.reject(new Error('Ajax错误'));
    } else {
      return response.data;
    }
  },
  error => {
    Message({
      message: '服务器返回错误',
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
